<template>
    <van-image
      width="100%"
      height="300"
      fit="cover"
      :src="product.thumbs_text"
    />

    <div class="detailbox">
      <h4>{{product.name}}</h4>
      <div class="price">
        单独购买：<em>￥</em>{{product.price}} |
        拼团价格：<em>￥</em>{{product.buy}}
      </div>
    </div>

    <div class="allkbox"></div>

    <!-- 商品规格 -->
    <div class="info_choice">
      <!-- Sku 商品规格 -->
      <div class="commodity" @click="SkuShow = true">
        <div class="opt">
          <div class="title wanl-gray">选择</div>
          <div class="option">
            <div class="selected">
              <div>
                <span>尺码</span>
                <span>颜色</span>
              </div>
            </div>
          </div>
        </div>
        <div class="wanl-gray">
          <img src="/assets/images/go.png" />
        </div>
      </div>
      <!-- 服务 -->
      <div class="commodity" @click="TipShow = true">
        <div class="opt">
          <div class="title wanl-gray">服务</div>
          <div class="option">
            <div class="selected">
              <div>
                <span>7天无理由退款</span>
                <span>·</span>
                <span>24小时内发货</span>
                <span>·</span>
                <span>假一赔十</span>
              </div>
            </div>
          </div>
        </div>
        <div class="wanl-gray">
          <img src="/assets/images/go.png" />
        </div>
      </div>
    </div>

    <div class="allkbox"></div>

    <!-- 选项卡 -->
    <van-tabs v-model:active="TabActive" type="card" color="#EE0A24">
      <van-tab title="产品参数">
        <div v-html="product.content"></div>
      </van-tab>
      <van-tab title="商品评价">
        <div class="rate" style="overflow-x: hidden;">
          <div class="rate-header">
            <div class="rate-score">
              <h4>与描述相符</h4>
              <strong>4.5</strong>
            </div>
            <div class="rate-graph">
              <van-rate v-model="rate" allow-half readonly />
            </div>
          </div>

          <div class="rate-content">
            <div v-if="comment">
              <div class="review-box" v-for="(item,key) in comment" :key="key">
                <div class="review-item">
                  <!-- 评论人 -->
                  <div class="from-whom">
                    <div class="avatar">
                      <img :src="item.business.avatar_text" alt="" />
                    </div>
                    <div class="name">{{item.business.nickname ? item.business.nickname : '暂无昵称'}}</div>
                  </div>

                  <!-- 评论内容 -->
                  <div class="review-details">
                    <div class="content">{{item.comment}}</div>
                    <div>
                        <img :src="item.thumbs_text" alt="">
                    </div>
                    <div class="time">{{item.comtime_text}}</div>
                    <van-rate v-model="item.rate" readonly />
                  </div>
                </div>
              </div>
            </div>
            <div v-else>
              <div class="rate-empty">该商品还没有人写评价呢</div>
            </div>
          </div>
        </div>
      </van-tab>
    </van-tabs>

    <!-- SKU -->
    <van-sku
      ref="SkuRef"
      v-model="SkuShow"
      :sku="sku"
      :properties="properties"
      :goods="goods"
      :goods-id="product.id"
      @add-cart="AddCart"
      @buy-clicked="Buy"
    >
      <template #sku-actions="props">
        <div class="van-sku-actions">
          <van-button square size="large" type="warning" @click="props.skuEventBus.emit('sku:addCart')">加入购物车</van-button>

          <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
          <van-button square size="large" type="danger" @click="props.skuEventBus.emit('sku:buy')">单独购买</van-button>

          <van-button square size="large" type="danger" @click="JoinTeam">参与拼团</van-button>
        </div>
      </template>
    </van-sku>

    <!-- 协议条款 -->
    <van-action-sheet v-model:show="TipShow" title="协议条款">
      <div class="ProductTip">
        三、我们如何使用信息 <br />
        四、我们如何共享信息<br />
        五、我们如何转让信息<br />
        六、我们如何公开披露信息<br />
        七、一般储存期限<br />
        八、我们如何确保您的信息安全<br />
        九、您能做什么<br />
        十、我们如何处理未成年人的个人信息<br />
        十一、您的个人信息的存储地点<br />
        十二、本隐私权政策不适用的范围<br />
        十三、本隐私权政策如何更新<br />
        十四、联系我们<br />
      </div>
    </van-action-sheet>

    <!-- 底部导航栏 -->
    <van-action-bar>
      <van-action-bar-icon icon="chat-o" text="客服" />

      <van-action-bar-icon icon="cart-o" @click="ToCart" text="购物车" :badge="product.cart" v-if="product.cart" />
      <van-action-bar-icon icon="cart-o" @click="ToCart" text="购物车" v-else />

      <van-action-bar-icon icon="star" text="已收藏" color="#ff5000" @click="collection" v-if="product.collection" />
      <van-action-bar-icon icon="star-o" text="收藏" @click="collection" v-else />

      <van-action-bar-button type="danger" text="立即购买" @click="SkuShow = true" />
    </van-action-bar>

</template>

<script setup>
  import VanSku from 'vant-sku';
  import 'vant-sku/dist/index.css'
  const { proxy } = getCurrentInstance();


  //商品id
  let proid = proxy.$route.query.proid ? proxy.$route.query.proid : 0
  let product = ref({})
  let comment = ref([])

  // 拼团ID
  let teamid = proxy.$cookies.get('teamid') ? proxy.$cookies.get('teamid') : 0;

  //选项卡
  let TabActive = ref(0)
  let rate = ref(4.5)

  //Sku
  let SkuShow = ref(false)
  let sku = ref({})
  let properties = ref([])
  let goods = ref({})
  let SkuRef = ref(null)

  //条款服务
  let TipShow = ref(false)

  //生命周期
  onBeforeMount(() => {
    info()
  })

  //获取商品详细
  const info = async () =>
  {
    var params = {proid}

    //判断是否有没有登录
    if(proxy.$business.value.id)
    {
      params.busid = proxy.$business.value.id
    }

    var result = await proxy.$POST({
      url: '/product/info',
      params: params
    })

    if(result.code == 0)
    {
      proxy.$fail({
        message: result.msg,
        duration: 1000,
        onClose: () => proxy.$router.go(-1)
      })
      return false
    }

    let ProductData = result.data.product
    let CommentData = result.data.comment
    let SkuData = result.data.sku
    let PropertiesData = result.data.properties


    //星级评分 需要给数值类型
    CommentData.map(item => item.rate = parseInt(item.rate))

    product.value = ProductData
    comment.value = CommentData

    // sku
    goods.value = {picture: ProductData.thumbs_text}
    sku.value = SkuData
    properties.value = Object.values(PropertiesData)
  }

  //添加收藏
  const collection = async () =>
  {
    if(!proxy.$business.value.id)
    {
      proxy.$fail('请先登录')
      return false
    }

    //请求
    var result = await proxy.$POST({
      url: '/product/collection',
      params: {
        busid: proxy.$business.value.id,
        collectid: proid,
      }
    })

    if(result.code == 0)
    {
      proxy.$fail(result.msg)
      return false
    }

    product.value.collection = result.data == 'add' ? true : false
  }

  //添加购物车
  const AddCart = async (SkuData) =>
  {
    //判断是否有登录
    if(!proxy.$business.value.id)
    {
      proxy.$fail('请先登录')
      return false
    }

    //判断是否有选择规格
    if(properties.value.length > 0 && !SkuData.selectedSkuComb)
    {
      proxy.$fail('请选择商品规格')
      return false
    }

    //购买数量
    var selectedNum = SkuData.selectedNum

    if(selectedNum <= 0)
    {
      proxy.$fail('购买数量不能小于等于0')
      return false
    }

    var relationids = []

    //有规格
    if(properties.value.length > 0)
    {
      var SkuProps = SkuData.selectedSkuComb.properties

      for(var item of SkuProps)
      {
        var id = item.v[0] ? item.v[0]['id'] : 0;
        if(id) relationids.push(id)
      }
    }

    //组装数据
    var params = {
      busid: proxy.$business.value.id,
      proid: proid,
      nums: selectedNum,
      relationids:relationids.join(','), //规格id
    }

    //发送请求
    var result = await proxy.$POST({
      url: '/cart/add',
      params
    })

    //隐藏弹出框
    SkuShow.value = false

    if(result.code == 0)
    {
      proxy.$fail(result.msg)
      return false
    }

    proxy.$success(result.msg)

    //更新购物车数量
    product.value.cart = result.data
  }

  //跳转购物车
  const ToCart = () => proxy.$router.push('/cart/index')

  // 单人购买
  const Buy = async (SkuData) =>
  {
    console.log('单人购买')
    console.log(SkuData)
  }

  // 参与拼团
  const JoinTeam = async () => {
    // 没有参与具体的拼团活动
    if (!teamid) {
      proxy.$router.push({path:'/team/index',query:{proid:product.value.id}})
      return false
    }

    var SkuData = SkuRef.value.getSkuData()

    //判断是否有登录
    if(!proxy.$business.value.id)
    {
      proxy.$fail('请先登录')
      return false
    }

    //判断是否有选择规格
    if(properties.value.length > 0 && !SkuData.selectedSkuComb)
    {
      proxy.$fail('请选择商品规格')
      return false
    }

    var relationids = []

    //有规格
    if(properties.value.length > 0)
    {
      var SkuProps = SkuData.selectedSkuComb.properties

      for(var item of SkuProps)
      {
        var id = item.v[0] ? item.v[0]['id'] : 0;
        if(id) relationids.push(id)
      }
    }

    // 规格ID 记录到cookie中
    // relationids: relationids.join(','), //规格id
    proxy.$cookies.set('relationids',relationids)

    //隐藏弹出框
    SkuShow.value = false

    proxy.$router.push({path: '/team/confirm', query: {proid: product.value.id}})

  }

</script>
